package com.lm.lua.controller;

import com.lm.lua.config.LuaScriptManager;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LuaController {

    @Autowired
    private LuaScriptManager luaScriptManager;

    @GetMapping("/greet")
    public String greet(@RequestParam String name) {
        // 加载脚本
        LuaValue script = luaScriptManager.loadScript("E:\\lk\\springboot-example\\lm-luaj\\src\\main\\resources\\scripts\\hello.lua");
        // 调用 greet 函数
        LuaValue result = luaScriptManager.executeFunction(script,"greet", LuaValue.valueOf(name));

        if (result.isnil()) {
            System.out.println("Function returned nil");
        } else {
            System.out.println("Result: " + result.tojstring());
        }

        return result.tojstring();
    }

    @GetMapping("/calculate")
    public String calculate(@RequestParam double a,
                            @RequestParam double b,
                            @RequestParam String operation) {
        // 加载脚本
        LuaValue script = luaScriptManager.loadScript("E:\\lk\\springboot-example\\lm-luaj\\src\\main\\resources\\scripts\\calculator.lua");

        // 调用 calculate 函数
        LuaValue result = luaScriptManager.executeFunction(script, "calculate",
                LuaValue.valueOf(a), LuaValue.valueOf(b), LuaValue.valueOf(operation));

        return result.tojstring();
    }
}
